import React, { useEffect, useState } from "react";
import { Spin, message, Button, Divider, Select, Input, DatePicker } from "antd";
import { get, put } from "../components/axios";
import "./Profile.css";
import dayjs from "dayjs";

export default function Profile() {
    // 你可以根据实际业务调整
    const departmentOptions = [
        { label: "摸鱼部", value: "摸鱼部" },
        { label: "技术部", value: "技术部" },
        { label: "产品部", value: "产品部" },
        { label: "运营部", value: "运营部" }
    ];

    const [user, setUser] = useState(null);
    const [loading, setLoading] = useState(true);
    // 记录正在编辑的字段
    const [editingField, setEditingField] = useState(null);
    const [editValue, setEditValue] = useState("");
    const [activeTab, setActiveTab] = useState("info"); // "info" 或 "notice"
    const [noticeSubTab, setNoticeSubTab] = useState("notice"); // "notice" | "private" | "atme"

    // 新增可选项
    const employeeRoleOptions = [
        { label: "普通成员", value: "普通成员" },
        { label: "管理员", value: "管理员" },
        { label: "部门主管", value: "部门主管" }
    ];
    const positionOptions = [
        { label: "前端开发工程师", value: "前端开发工程师" },
        { label: "后端开发工程师", value: "后端开发工程师" },
        { label: "产品经理", value: "产品经理" },
        { label: "测试工程师", value: "测试工程师" }
    ];
    const superiorOptions = [
        { label: "李四", value: "李四" },
        { label: "王五", value: "王五" },
        { label: "赵六", value: "赵六" }
    ];

    // 可编辑字段扩展
    const editableFields = ["phone", "postBox", "deparTment", "EmployeeRoles", "posiTion", "SuperiorAuthority", "initialPassword", "entryTime"];

    useEffect(() => {
        async function fetchUser() {
            try {
                const res = await get('/users/users');
                if (res && res.data && res.data.length > 0) {
                    setUser(res.data[0]);
                } else {
                    setUser(null);
                }
            } catch (err) {
                message.error("获取个人信息失败");
                setUser(null);
            } finally {
                setLoading(false);
            }
        }
        fetchUser();
    }, []);

    // 保存编辑
    const handleSave = async (field, value) => {
        if (!user) return;
        const newValue = value !== undefined ? value : editValue;
        if (newValue === user[field]) {
            setEditingField(null);
            return;
        }
        // 手机号正则校验
        if (field === "phone") {
            const phoneReg = /^1[3-9]\d{9}$/;
            if (!phoneReg.test(newValue)) {
                message.error("请输入有效的11位手机号");
                return;
            }
        }
        try {
            if (!["deparTment", "phone", "postBox", "EmployeeRoles", "posiTion", "SuperiorAuthority", "initialPassword", "entryTime"].includes(field)) {
                message.error("该字段不可编辑");
                setEditingField(null);
                return;
            }
            const updateData = {
                _id: user._id,
                [field]: newValue
            };
            const res = await put('/users/updateUsers', updateData);
            if (res && res.code === 200) {
                setUser({ ...user, [field]: newValue });
                message.success("修改成功");
            } else {
                message.error(res.msg || "修改失败");
            }
        } catch {
            message.error("网络错误，修改失败");
        }
        setEditingField(null);
    };

    if (loading) {
        return (
            <div className="profile-admin-root">
                <Spin size="large" />
            </div>
        );
    }

    if (!user) {
        return (
            <div className="profile-admin-root" style={{ color: "#888" }}>
                暂无个人信息
            </div>
        );
    }

    const avatarText = (user.userName || user.username || "U").charAt(0).toUpperCase();

    return (
        <div className="profile-root">
            <div className="profile-avatar-section">
                <div className="profile-avatar">{avatarText}</div>
                <div className="profile-username">{user.userName || user.username}</div>
                <div className="profile-jobnumber">工号：{user.jobNumber}</div>
                <div className="profile-role">{user.roles}</div>
                <div className="profile-menu">
                    <div
                        className={activeTab === "notice" ? "profile-menu-item active" : "profile-menu-item"}
                        onClick={() => setActiveTab("notice")}
                    >
                        通知信息
                    </div>
                    <div
                        className={activeTab === "info" ? "profile-menu-item active" : "profile-menu-item"}
                        onClick={() => setActiveTab("info")}
                    >
                        个人信息
                    </div>
                </div>
            </div>
            <div className="profile-info-section">
                {activeTab === "info" ? (
                    <>
                        <ProfileRow
                            label="员工角色"
                            value={user.EmployeeRoles}
                            field="EmployeeRoles"
                            editable={editableFields.includes("EmployeeRoles")}
                            editingField={editingField}
                            setEditingField={setEditingField}
                            editValue={editValue}
                            setEditValue={setEditValue}
                            onSave={handleSave}
                            options={employeeRoleOptions}
                        />
                        <ProfileRow
                            label="部门"
                            value={user.deparTment}
                            field="deparTment"
                            editable={editableFields.includes("deparTment")}
                            editingField={editingField}
                            setEditingField={setEditingField}
                            editValue={editValue}
                            setEditValue={setEditValue}
                            onSave={handleSave}
                            options={departmentOptions}
                        />
                        <ProfileRow
                            label="职位"
                            value={user.posiTion}
                            field="posiTion"
                            editable={editableFields.includes("posiTion")}
                            editingField={editingField}
                            setEditingField={setEditingField}
                            editValue={editValue}
                            setEditValue={setEditValue}
                            onSave={handleSave}
                            options={positionOptions}
                        />
                        <ProfileRow
                            label="手机号"
                            value={user.phone}
                            field="phone"
                            editable={editableFields.includes("phone")}
                            editingField={editingField}
                            setEditingField={setEditingField}
                            editValue={editValue}
                            setEditValue={setEditValue}
                            onSave={handleSave}
                            inputWidth={160}
                        />
                        <EmailEditRow
                            value={user.postBox || user.email}
                            field="postBox"
                            editable={editableFields.includes("postBox")}
                            editingField={editingField}
                            setEditingField={setEditingField}
                            editValue={editValue}
                            setEditValue={setEditValue}
                            onSave={handleSave}
                        />
                        <ProfileRow
                            label="入职时间"
                            value={user.entryTime ? String(user.entryTime).slice(0,10) : "-"}
                            field="entryTime"
                            editable={editableFields.includes("entryTime")}
                            editingField={editingField}
                            setEditingField={setEditingField}
                            editValue={editValue}
                            setEditValue={setEditValue}
                            onSave={handleSave}
                            type="date"
                        />
                        <ProfileRow
                            label="初始密码"
                            value={user.initialPassword}
                            field="initialPassword"
                            editable={editableFields.includes("initialPassword")}
                            editingField={editingField}
                            setEditingField={setEditingField}
                            editValue={editValue}
                            setEditValue={setEditValue}
                            onSave={handleSave}
                            type="input"
                        />
                        <ProfileRow
                            label="直属上级"
                            value={user.SuperiorAuthority}
                            field="SuperiorAuthority"
                            editable={editableFields.includes("SuperiorAuthority")}
                            editingField={editingField}
                            setEditingField={setEditingField}
                            editValue={editValue}
                            setEditValue={setEditValue}
                            onSave={handleSave}
                            options={superiorOptions}
                        />
                    </>
                ) : (
                    <>
                        <div className="notice-tabs">
                            <div className={noticeSubTab === "private" ? "notice-tab active" : "notice-tab"} onClick={() => setNoticeSubTab("private")}>私信</div>
                            <div className={noticeSubTab === "notice" ? "notice-tab active" : "notice-tab"} onClick={() => setNoticeSubTab("notice")}>通知</div>
                            <div className={noticeSubTab === "atme" ? "notice-tab active" : "notice-tab"} onClick={() => setNoticeSubTab("atme")}>@我</div>
                        </div>
                        <div className="notice-content">
                            {noticeSubTab === "private" && <div>暂无私信</div>}
                            {noticeSubTab === "notice" && <div>暂无通知</div>}
                            {noticeSubTab === "atme" && <div>暂无@我相关内容</div>}
                        </div>
                    </>
                )}
            </div>
        </div>
    );
}

// 可编辑的行
function ProfileRow({
    label, value, field, editable, editingField, setEditingField, editValue, setEditValue, onSave, options, inputWidth, type
}) {
    const handleDoubleClick = () => {
        if (editable) {
            setEditingField(field);
            setEditValue(value || "");
        }
    };
    const handleKeyDown = (e) => {
        if (e.key === "Enter") {
            onSave(field, editValue);
        }
    };
    const handleBlur = () => {
        onSave(field, editValue);
    };
    const handleSelectChange = (val) => {
        setEditValue(val);
        onSave(field, val);
    };

    return (
        <div className="profile-admin-row">
            <div className="profile-admin-label">{label}</div>
            {editable && editingField === field ? (
                options ? (
                    <Select
                        value={editValue}
                        style={{ minWidth: inputWidth || 120 }}
                        options={options}
                        onChange={handleSelectChange}
                        onBlur={handleBlur}
                        popupMatchSelectWidth={false}
                        autoFocus
                    />
                ) : type === "input" ? (
                    <Input
                        value={editValue}
                        autoFocus
                        onChange={e => setEditValue(e.target.value)}
                        onKeyDown={handleKeyDown}
                        onBlur={handleBlur}
                        style={{ width: inputWidth || 120 }}
                    />
                ) : type === "date" ? (
                    <DatePicker
                        value={editValue ? dayjs(editValue) : null}
                        onChange={(_, dateString) => setEditValue(dateString)}
                        onBlur={handleBlur}
                        style={{ width: inputWidth || 140 }}
                        format="YYYY-MM-DD"
                        autoFocus
                    />
                ) : (
                    <Input
                        value={editValue}
                        autoFocus
                        onChange={e => setEditValue(e.target.value)}
                        onKeyDown={handleKeyDown}
                        onBlur={handleBlur}
                        style={{ width: inputWidth || 120 }}
                    />
                )
            ) : (
                <div
                    className={editable ? "profile-admin-editable" : "profile-admin-value"}
                    onDoubleClick={handleDoubleClick}
                    title={editable ? "双击可编辑" : ""}
                    style={editable ? { background: "#f6f6f6", borderRadius: 3, padding: "0 4px" } : {}}
                >
                    {value || <span style={{ color: "#bbb" }}>-</span>}
                </div>
            )}
        </div>
    );
}

// 分割邮箱
function splitEmail(email = "") {
    const [name = "", domain = ""] = email.split("@");
    return { name, domain: domain ? "@" + domain : "" };
}

// 合成邮箱
function joinEmail(name, domain) {
    return name && domain ? `${name}${domain}` : "";
}

const emailDomainOptions = [
    { label: "@company.com", value: "@company.com" },
    { label: "@gmail.com", value: "@gmail.com" },
    { label: "@qq.com", value: "@qq.com" }
];

export function EmailEditRow({
    value, editable, editingField, setEditingField, editValue, setEditValue, onSave, field
}) {
    const { name, domain } = splitEmail(editValue || value);

    const handleNameChange = (e) => {
        setEditValue(joinEmail(e.target.value, domain));
    };
    const handleDomainChange = (val) => {
        setEditValue(joinEmail(name, val));
    };
    const handleSaveClick = () => {
        onSave(field, joinEmail(name, domain));
    };
    const handleKeyDown = (e) => {
        if (e.key === "Enter") {
            onSave(field, joinEmail(name, domain));
        }
    };
    const handleCancel = () => {
        setEditingField(null);
    };

    return (
        <div className="profile-admin-row">
            <div className="profile-admin-label">邮箱</div>
            {editingField === field ? (
                <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
                    <Input
                        value={name}
                        autoFocus
                        onChange={handleNameChange}
                        onKeyDown={handleKeyDown}
                        style={{ width: 100 }}
                        placeholder="邮箱名"
                    />
                    <Select
                        value={domain || emailDomainOptions[0].value}
                        style={{ width: 120 }}
                        options={emailDomainOptions}
                        onChange={handleDomainChange}
                        popupMatchSelectWidth={false}
                    />
                    <Button type="primary" size="small" onClick={handleSaveClick} style={{ marginLeft: 8 }}>
                        保存
                    </Button>
                    <Button size="small" onClick={handleCancel} style={{ marginLeft: 4 }}>
                        取消
                    </Button>
                </div>
            ) : (
                <div
                    className="profile-admin-editable"
                    onDoubleClick={() => {
                        if (editable) {
                            setEditingField(field);
                            setEditValue(value || "");
                        }
                    }}
                    title="双击可编辑"
                    style={{ background: "#f6f6f6", borderRadius: 3, padding: "0 4px" }}
                >
                    {value || <span style={{ color: "#bbb" }}>-</span>}
                </div>
            )}
        </div>
    );
}
